#! /bin/bash

function _sshpass() {
    # $1: cmd
    # $2: password
    echo "sshpass -p $2 $1"
}

function _cmd_sync_ssh_to_ssh() {
    # $1: src host
    # $2: src username
    # $3: src password
    # $4: src path
    # $5: dst host
    # $6: dst username
    # $7: dst password
    # $8: dst path

    _src_host=$1
    _src_username=$2
    _src_password=$3
    _src_path=$4
    _dst_host=$5
    _dst_username=$6
    _dst_password=$7
    _dst_path=$8

    # create ssh cmd
    _ssh_src="ssh $_src_username@$_src_host"
    _ssh_dst="ssh $_dst_username@$_dst_host"

    # create mkdir cmd
    _cmd_mkdir=$(_sshpass "$_ssh_dst" "$_dst_password")
    _cmd_mkdir="$_cmd_mkdir  \"mkdir -p $_dst_path\""
    echo $_cmd_mkdir

    # create sync cmd
    _cmd_on_dst="rsync -av --delete -e $_ssh_src:$_src_path $_dst_path"
    if [ ! -z "$_src_password" ]; then
        _cmd_on_dst=$(_sshpass "$_cmd_on_dst" "$_src_password")
        #_cmd_on_dst="sshpass -p $_src_password $_cmd_on_dst"
    fi

    _cmd_rsync="$_ssh_dst \"$_cmd_on_dst\""
    if [ ! -z "$_dst_password" ]; then
        _cmd_rsync=$(_sshpass "$_cmd_rsync" "$_dst_password")
        #_cmd_rsync="sshpass -p $_dst_password $_cmd_rsync"
    fi

    echo $_cmd_rsync
}

function _sync_ssh_to_ssh() {
    # $1: src host
    # $2: src username
    # $3: src password
    # $4: src path
    # $5: dst host
    # $6: dst username
    # $7: dst password
    # $8: dst path

    eval $(_cmd_sync_ssh_to_ssh "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8")
}
